package com.example.hrsystem.ui.home;

import android.content.Context;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.hrsystem.data.model.TaskItem;
import com.example.hrsystem.ui.attendance.AttendanceDetailActivity;
import com.example.hrsystem.ui.approval.leave.LeaveRequestListActivity;
import com.example.hrsystem.ui.approval.overtime.OvertimeRequestListActivity;
import com.example.hrsystem.ui.approval.businesstravel.BusinessTravelRequestListActivity;
import com.example.hrsystem.ui.task.TaskDetailActivity;
import com.example.hrsystem.ui.task.TaskListActivity;
import com.example.hrsystem.ui.task.TaskViewModel;
import com.example.hrsystem.workflow.ui.WorkflowActivity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import androidx.viewpager2.widget.ViewPager2;

import com.example.hrsystem.R;
import com.example.hrsystem.data.model.AttendanceRecord;
import com.example.hrsystem.data.model.User;
import com.example.hrsystem.data.source.AppDatabase;

import android.app.AlertDialog;
import android.content.Intent;
import android.text.Layout;
import android.view.Gravity;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 首页Fragment
 * 展示欢迎信息、功能入口和待办事项统计
 */
public class HomeFragment extends Fragment {

    private TextView dateTextView;
// 统计信息
    private TextView completedTasksTextView;
    private TextView attendanceRateTextView;
    private TextView checkInTimeTextView;
    private TextView checkOutTimeTextView;
    private TextView todoCountTextView;
    private TextView viewAllTodoTextView;
    private LinearLayout todoListContainer;
    private SharedPreferences sharedPreferences;
    private AppDatabase database;
    private boolean isCheckedIn = false;
    private boolean isCheckedOut = false;
    private Handler refreshHandler;
    private Runnable refreshRunnable;
    private static final String KEY_CHECKED_IN = "checked_in";
    private static final String KEY_CHECKED_OUT = "checked_out";
    private static final String KEY_CHECK_IN_TIME = "check_in_time";
    private static final String KEY_CHECK_OUT_TIME = "check_out_time";
    private static final String KEY_CURRENT_DATE = "current_date";
    private static final long REFRESH_INTERVAL = 5000; // 5秒刷新一次
    private String currentEmployeeId; // 登录用户的员工ID
    private String prefsName; // 基于用户ID的SharedPreferences名称
    
    // 轮播图相关变量
    private ViewPager2 carouselViewPager;
    private CarouselAdapter carouselAdapter;
    private Handler carouselHandler;
    private Runnable autoScrollRunnable;
    private static final long AUTO_SCROLL_DELAY = 3000; // 3秒自动切换一次
    private LinearLayout indicatorContainer;
    private ImageView[] indicators;
    private int[] carouselImages = {
        R.drawable.build_school,
        R.drawable.study_teach,
        R.drawable.build_school,
        R.drawable.study_teach,
    };
    
    // 任务相关变量
    private TaskViewModel taskViewModel;
    
    // 工作流按钮
    private Button workflowButton;
    // 快捷功能按钮
    private Button leaveRequestButton;
    private Button overtimeRequestButton;
    private Button businessTravelRequestButton;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.d("HomeFragment", "onCreateView called");
        
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        
        try {
            // 显示初始化开始的Toast
//            if (getActivity() != null) {
//                Toast.makeText(getActivity(), "首页Fragment开始初始化", Toast.LENGTH_SHORT).show();
//            }

            // 初始化数据库和SharedPreferences
            if (getActivity() != null) {
                database = AppDatabase.getDatabase(getActivity().getApplicationContext());
                
                // 获取登录用户信息
                SharedPreferences userPrefs = getActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
                currentEmployeeId = userPrefs.getString("employee_id", "1001"); // 默认值仅用于开发测试
                
                // 创建基于用户ID的SharedPreferences名称，确保数据隔离
                prefsName = "attendance_prefs_" + currentEmployeeId;
                sharedPreferences = getActivity().getSharedPreferences(prefsName, Context.MODE_PRIVATE);
                
                Log.d("HomeFragment", "Database and SharedPreferences initialized for user: " + currentEmployeeId);
            }

            // 初始化ViewModel
            taskViewModel = new ViewModelProvider(this).get(TaskViewModel.class);
            
            // 初始化UI组件
            initViews(view);
            // 初始化轮播图
            initCarousel(view);
            Log.d("HomeFragment", "UI components initialized");

            // 更新日期
            updateDateInfo();

            // 更新统计数据
            updateStatistics();

            // 恢复打卡状态
            restoreAttendanceState();
            
            // 从数据库加载今日打卡记录
            loadTodayAttendanceRecord();

            // 设置功能按钮点击事件
            setupButtons();
            
            // 设置定时刷新机制
            setupAutoRefresh();
            
            // 观察任务数据变化
            observeTaskData();

            // 显示初始化完成的Toast
//            if (getActivity() != null) {
//                Toast.makeText(getActivity(), "首页Fragment初始化完成", Toast.LENGTH_SHORT).show();
//            }

            Log.d("HomeFragment", "Fragment initialization completed");
        } catch (Exception e) {
            Log.e("HomeFragment", "初始化异常: " + e.getMessage(), e);
//            if (getActivity() != null) {
//                Toast.makeText(getActivity(), "首页加载失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
//            }
        }
        
        return view;
    }

    /**
     * 初始化UI组件
     */
    private void initViews(View view) {
        dateTextView = view.findViewById(R.id.date_text_view);
// 统计信息
        completedTasksTextView = view.findViewById(R.id.completed_tasks_text_view);
        attendanceRateTextView = view.findViewById(R.id.attendance_rate_text_view);
        checkInTimeTextView = view.findViewById(R.id.check_in_time_text_view);
        checkOutTimeTextView = view.findViewById(R.id.check_out_time_text_view);
        todoCountTextView = view.findViewById(R.id.todo_count_text_view);
        viewAllTodoTextView = view.findViewById(R.id.view_all_todo_text_view);
        todoListContainer = view.findViewById(R.id.todo_list_container);
        carouselViewPager = view.findViewById(R.id.carousel_view_pager);
        indicatorContainer = view.findViewById(R.id.carousel_indicator_container);
        workflowButton = view.findViewById(R.id.workflow_button); // 初始化工作流按钮
        // 初始化快捷功能按钮
        leaveRequestButton = view.findViewById(R.id.leave_request_button);
        overtimeRequestButton = view.findViewById(R.id.overtime_request_button);
        businessTravelRequestButton = view.findViewById(R.id.business_travel_request_button);
        
        // 设置已完成任务数点击事件
        completedTasksTextView.setOnClickListener(v -> {
            // 跳转到已完成任务详情页面
            Intent intent = new Intent(getActivity(), TaskListActivity.class);
            intent.putExtra("filter_status", "已完成");
            startActivity(intent);
        });
        
        // 设置出勤率点击事件
        attendanceRateTextView.setOnClickListener(v -> {
            // 跳转到考勤详情页面
            Intent intent = new Intent(getActivity(), AttendanceDetailActivity.class);
            startActivity(intent);
        });
        
        // 尝试隐藏打卡按钮（如果存在）
        Button checkInButton = view.findViewById(R.id.check_in_button);
        Button checkOutButton = view.findViewById(R.id.check_out_button);
        if (checkInButton != null) checkInButton.setVisibility(View.GONE);
        if (checkOutButton != null) checkOutButton.setVisibility(View.GONE);
        
        // 设置工作流按钮点击事件
        if (workflowButton != null) {
            workflowButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 跳转到工作流页面
                    Intent intent = new Intent(getContext(), WorkflowActivity.class);
                    startActivity(intent);
                }
            });
        }
    }

    /**
     * 从数据库加载今日打卡记录
     */
    private void loadTodayAttendanceRecord() {
        if (database == null) return;
        
        // 异步查询今日打卡记录
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    AttendanceRecord record = database.attendanceDao().getTodayAttendanceRecordSync(currentEmployeeId);
                    if (record != null) {
                        updateUIWithRecord(record);
                    }
                } catch (Exception e) {
                    Log.e("HomeFragment", "加载打卡记录失败: " + e.getMessage(), e);
                }
            }
        }).start();
    }

    /**
     * 更新UI显示打卡记录
     */
    private void updateUIWithRecord(AttendanceRecord record) {
        if (getActivity() == null) return;
        
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (record.getCheckInTime() != null) {
                        String checkInTimeStr = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(record.getCheckInTime());
                        checkInTimeTextView.setText(checkInTimeStr);
                        isCheckedIn = true;
                    }
                    if (record.getCheckOutTime() != null) {
                        String checkOutTimeStr = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(record.getCheckOutTime());
                        checkOutTimeTextView.setText(checkOutTimeStr);
                        isCheckedOut = true;
                    }
                } catch (Exception e) {
                    Log.e("HomeFragment", "更新打卡记录UI失败: " + e.getMessage(), e);
                }
            }
        });
    }

    /**
     * 更新日期信息
     */
    private void updateDateInfo() {
        try {
            // 获取当前日期
            Calendar calendar = Calendar.getInstance();
            Date currentDate = calendar.getTime();
            
            // 格式化日期
            String formattedDate = new SimpleDateFormat("yyyy年MM月dd日 EEEE", Locale.getDefault()).format(currentDate);
            
            // 更新日期TextView
            if (dateTextView != null) {
                dateTextView.setText(formattedDate);
            }
        } catch (Exception e) {
            Log.e("HomeFragment", "更新日期信息失败: " + e.getMessage(), e);
        }
    }

    /**
     * 更新统计数据
     */
    private void updateStatistics() {
        // 这里应该从数据库或API获取实际的统计数据
        completedTasksTextView.setText("5");
        todoCountTextView.setText("(2)");
        
        // 异步计算实际出勤率
        calculateAttendanceRate();
        
        // 初始化待办事项列表
        initTodoList();
    }

    /**
     * 初始化待办事项列表
     */
    private void initTodoList() {
        // 清空容器
        todoListContainer.removeAllViews();
        
        // 从ViewModel获取待办事项数据
        // 这里使用当前用户ID，实际项目中应从登录信息获取
        String currentUserId = currentEmployeeId; // 使用已有的员工ID
        taskViewModel.getTasksByAssigneeId(currentUserId).observe(getViewLifecycleOwner(), taskItems -> {
            if (taskItems != null && !taskItems.isEmpty()) {
                // 显示最多3个待办事项
                int displayCount = Math.min(3, taskItems.size());
                for (int i = 0; i < displayCount; i++) {
                    addTodoItem(taskItems.get(i));
                }
                
                // 更新待办事项数量
                todoCountTextView.setText("(" + taskItems.size() + ")");
            } else {
                // 如果没有待办事项，添加一个提示
                todoCountTextView.setText("(0)");
                TextView emptyTextView = new TextView(getContext());
                emptyTextView.setText("暂无待办事项");
                emptyTextView.setTextSize(14);
                emptyTextView.setTextColor(getResources().getColor(R.color.colorTextSecondary));
                emptyTextView.setPadding(0, 16, 0, 16);
                emptyTextView.setGravity(Gravity.CENTER);
                todoListContainer.addView(emptyTextView);
            }
        });
    }

    /**
     * 添加待办事项到列表
     */
    private void addTodoItem(TaskItem taskItem) {
        // 创建待办事项视图
        View todoItemView = LayoutInflater.from(getContext()).inflate(R.layout.item_task, todoListContainer, false);
        
        // 设置任务信息
        TextView titleTextView = todoItemView.findViewById(R.id.task_title_text_view);
        TextView createTimeTextView = todoItemView.findViewById(R.id.create_time_text_view);
        TextView deadlineTextView = todoItemView.findViewById(R.id.deadline_text_view);
        TextView typeTextView = todoItemView.findViewById(R.id.task_type_text_view);
        TextView statusTextView = todoItemView.findViewById(R.id.task_status_text_view);
        TextView priorityTextView = todoItemView.findViewById(R.id.priority_text_view);
        
        // 设置文本内容
        if (titleTextView != null) {
            titleTextView.setText(taskItem.getTitle());
        }
        if (createTimeTextView != null) {
            createTimeTextView.setText(formatDate(taskItem.getCreateTime()));
        }
        if (deadlineTextView != null && taskItem.getDeadline() != null) {
            deadlineTextView.setText(formatDate(taskItem.getDeadline()));
        }
        if (typeTextView != null) {
            typeTextView.setText(taskItem.getTaskType());
        }
        if (statusTextView != null) {
            statusTextView.setText(taskItem.getStatus());
        }
        if (priorityTextView != null) {
            priorityTextView.setText(taskItem.getPriority());
            // 根据优先级设置不同颜色
            if ("高".equals(taskItem.getPriority())) {
                priorityTextView.setTextColor(getResources().getColor(R.color.colorAccent));
                priorityTextView.setBackgroundResource(R.drawable.priority_high_background);
            } else if ("低".equals(taskItem.getPriority())) {
                priorityTextView.setTextColor(getResources().getColor(R.color.colorSuccess));
                priorityTextView.setBackgroundResource(R.drawable.priority_low_background);
            } else {
                priorityTextView.setTextColor(getResources().getColor(R.color.colorPrimary));
                priorityTextView.setBackgroundResource(R.drawable.priority_medium_background);
            }
        }
        
        // 设置点击事件
        todoItemView.setOnClickListener(v -> {
            // 点击待办事项跳转到详情页
            Intent intent = new Intent(getContext(), TaskDetailActivity.class);
            intent.putExtra("taskId", taskItem.getId());
            startActivity(intent);
        });
        
        // 添加长按事件用于删除
        todoItemView.setOnLongClickListener(v -> {
            showDeleteConfirmation(taskItem);
            return true;
        });
        
        // 添加到容器中
        todoListContainer.addView(todoItemView);
    }

    /**
     * 格式化日期
     */
    private String formatDate(Date date) {
        if (date == null) return "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
        return sdf.format(date);
    }

    /**
     * 显示删除确认对话框
     */
    private void showDeleteConfirmation(TaskItem taskItem) {
        if (getActivity() == null) return;
        
        new AlertDialog.Builder(getActivity())
                .setTitle("确认删除")
                .setMessage("确定要删除任务 \"" + taskItem.getTitle() + "\" 吗？")
                .setPositiveButton("删除", (dialog, which) -> {
                    // 删除任务
                    taskViewModel.deleteTask(taskItem);
                    Toast.makeText(getContext(), "任务已删除", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 恢复打卡状态
     */
    private void restoreAttendanceState() {
        try {
            // 获取当前日期
            String currentDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
            
            // 检查是否是同一天
            String savedDate = sharedPreferences.getString(KEY_CURRENT_DATE, "");
            if (currentDate.equals(savedDate)) {
                // 恢复打卡状态
                isCheckedIn = sharedPreferences.getBoolean(KEY_CHECKED_IN, false);
                isCheckedOut = sharedPreferences.getBoolean(KEY_CHECKED_OUT, false);
                
                // 恢复打卡时间
                String checkInTime = sharedPreferences.getString(KEY_CHECK_IN_TIME, "未签到");
                String checkOutTime = sharedPreferences.getString(KEY_CHECK_OUT_TIME, "未签退");
                
                if (checkInTimeTextView != null) {
                    checkInTimeTextView.setText(checkInTime);
                }
                if (checkOutTimeTextView != null) {
                    checkOutTimeTextView.setText(checkOutTime);
                }
            } else {
                // 不是同一天，重置状态
                resetAttendanceState();
            }
        } catch (Exception e) {
            Log.e("HomeFragment", "恢复打卡状态失败: " + e.getMessage(), e);
        }
    }

    /**
     * 重置打卡状态
     */
    private void resetAttendanceState() {
        try {
            isCheckedIn = false;
            isCheckedOut = false;
            
            if (checkInTimeTextView != null) {
                checkInTimeTextView.setText("未签到");
            }
            if (checkOutTimeTextView != null) {
                checkOutTimeTextView.setText("未签退");
            }
            
            // 保存重置后的状态
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putBoolean(KEY_CHECKED_IN, false);
            editor.putBoolean(KEY_CHECKED_OUT, false);
            editor.putString(KEY_CHECK_IN_TIME, "未签到");
            editor.putString(KEY_CHECK_OUT_TIME, "未签退");
            editor.putString(KEY_CURRENT_DATE, new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date()));
            editor.apply();
        } catch (Exception e) {
            Log.e("HomeFragment", "重置打卡状态失败: " + e.getMessage(), e);
        }
    }

    /**
     * 设置功能按钮点击事件
     */
    private void setupButtons() {
        if (viewAllTodoTextView != null) {
            viewAllTodoTextView.setOnClickListener(v -> viewAllTodos());
        }
        
        // 设置快捷功能按钮点击事件
        if (leaveRequestButton != null) {
            leaveRequestButton.setOnClickListener(v -> navigateToLeaveRequest());
        }
        
        if (overtimeRequestButton != null) {
            overtimeRequestButton.setOnClickListener(v -> navigateToOvertimeRequest());
        }
        
        if (businessTravelRequestButton != null) {
            businessTravelRequestButton.setOnClickListener(v -> navigateToBusinessTravelRequest());
        }
    }
    
    /**
     * 跳转到请假申请页面
     */
    private void navigateToLeaveRequest() {
        try {
            Intent intent = new Intent(getContext(), LeaveRequestListActivity.class);
            startActivity(intent);
            Log.d("HomeFragment", "跳转到请假申请页面");
        } catch (Exception e) {
            Log.e("HomeFragment", "跳转到请假申请页面失败: " + e.getMessage(), e);
            if (getActivity() != null) {
                Toast.makeText(getActivity(), "无法打开请假申请页面", Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    /**
     * 跳转到加班申请页面
     */
    private void navigateToOvertimeRequest() {
        try {
            Intent intent = new Intent(getContext(), OvertimeRequestListActivity.class);
            startActivity(intent);
            Log.d("HomeFragment", "跳转到加班申请页面");
        } catch (Exception e) {
            Log.e("HomeFragment", "跳转到加班申请页面失败: " + e.getMessage(), e);
            if (getActivity() != null) {
                Toast.makeText(getActivity(), "无法打开加班申请页面", Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    /**
     * 跳转到出差申请页面
     */
    private void navigateToBusinessTravelRequest() {
        try {
            Intent intent = new Intent(getContext(), BusinessTravelRequestListActivity.class);
            startActivity(intent);
            Log.d("HomeFragment", "跳转到出差申请页面");
        } catch (Exception e) {
            Log.e("HomeFragment", "跳转到出差申请页面失败: " + e.getMessage(), e);
            if (getActivity() != null) {
                Toast.makeText(getActivity(), "无法打开出差申请页面", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 查看全部待办事项
     */
    private void viewAllTodos() {
        // 跳转到待办事项列表页面
        Intent intent = new Intent(getContext(), TaskListActivity.class);
        startActivity(intent);
    }
    
    /**
     * 初始化轮播图
     */
    private void initCarousel(View view) {
        try {
            // 创建适配器
            carouselAdapter = new CarouselAdapter(carouselImages);
            carouselViewPager.setAdapter(carouselAdapter);
            
            // 设置初始位置为中间，这样可以向左滑动
            int initialPosition = Integer.MAX_VALUE / 2;
            initialPosition -= (initialPosition % carouselImages.length);
            carouselViewPager.setCurrentItem(initialPosition, false);
            
            // 创建指示器
            createIndicators(carouselImages.length);
            
            // 设置页面变化监听
            carouselViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
                @Override
                public void onPageSelected(int position) {
                    super.onPageSelected(position);
                    updateIndicators(position % carouselImages.length);
                }
            });
            
            // 设置自动轮播
            carouselHandler = new Handler(Looper.getMainLooper());
            autoScrollRunnable = new Runnable() {
                @Override
                public void run() {
                    carouselViewPager.setCurrentItem(carouselViewPager.getCurrentItem() + 1, true);
                    carouselHandler.postDelayed(this, AUTO_SCROLL_DELAY);
                }
            };
            
            Log.d("HomeFragment", "轮播图初始化完成");
        } catch (Exception e) {
            Log.e("HomeFragment", "轮播图初始化失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 创建指示器
     */
    private void createIndicators(int count) {
        try {
            indicatorContainer.removeAllViews();
            indicators = new ImageView[count];
            
            for (int i = 0; i < count; i++) {
                indicators[i] = new ImageView(getContext());
                indicators[i].setImageResource(R.drawable.indicator_inactive);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT
                );
                params.setMargins(8, 0, 8, 0);
                indicators[i].setLayoutParams(params);
                indicatorContainer.addView(indicators[i]);
            }
            
            // 设置第一个指示器为选中状态
            if (indicators.length > 0) {
                indicators[0].setImageResource(R.drawable.indicator_active);
            }
        } catch (Exception e) {
            Log.e("HomeFragment", "创建指示器失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 更新指示器
     */
    private void updateIndicators(int position) {
        try {
            for (int i = 0; i < indicators.length; i++) {
                if (i == position) {
                    indicators[i].setImageResource(R.drawable.indicator_active);
                } else {
                    indicators[i].setImageResource(R.drawable.indicator_inactive);
                }
            }
        } catch (Exception e) {
            Log.e("HomeFragment", "更新指示器失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 设置定时刷新机制
     */
    private void setupAutoRefresh() {
        try {
            refreshHandler = new Handler(Looper.getMainLooper());
            refreshRunnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        // 刷新统计数据
                        updateStatistics();
                        
                        // 刷新打卡记录
                        loadTodayAttendanceRecord();
                        
                        // 继续定时刷新
                        refreshHandler.postDelayed(this, REFRESH_INTERVAL);
                    } catch (Exception e) {
                        Log.e("HomeFragment", "定时刷新失败: " + e.getMessage(), e);
                    }
                }
            };
            
            // 启动定时刷新
            refreshHandler.postDelayed(refreshRunnable, REFRESH_INTERVAL);
        } catch (Exception e) {
            Log.e("HomeFragment", "设置定时刷新失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 观察任务数据变化
     */
    private void observeTaskData() {
        try {
            // 观察任务数据变化，当数据变化时更新UI
            taskViewModel.getAllTasks().observe(getViewLifecycleOwner(), taskItems -> {
                // 数据变化时更新统计数据和待办事项列表
                updateStatistics();
            });
        } catch (Exception e) {
            Log.e("HomeFragment", "观察任务数据失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    public void onResume() {
        super.onResume();
        // 启动轮播图自动播放
        if (carouselHandler != null && autoScrollRunnable != null) {
            carouselHandler.postDelayed(autoScrollRunnable, AUTO_SCROLL_DELAY);
        }
    }
    
    @Override
    public void onPause() {
        super.onPause();
        // 停止轮播图自动播放
        if (carouselHandler != null && autoScrollRunnable != null) {
            carouselHandler.removeCallbacks(autoScrollRunnable);
        }
        
        // 停止定时刷新
        if (refreshHandler != null && refreshRunnable != null) {
            refreshHandler.removeCallbacks(refreshRunnable);
        }
    }
    
    /**
     * 计算并更新出勤率
     */
    private void calculateAttendanceRate() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (database == null) return;
                    
                    // 计算本月第一天和最后一天
                    Calendar calendar = Calendar.getInstance();
                    calendar.set(Calendar.DAY_OF_MONTH, 1);
                    Date startDate = calendar.getTime();
                    
                    calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
                    Date endDate = calendar.getTime();
                    
                    // 从数据库获取本月打卡记录
                    List<AttendanceRecord> records = database.attendanceDao()
                            .getAttendanceRecordsByDateRangeSync(startDate, endDate, currentEmployeeId);
                    
                    // 统计正常打卡天数
                    int normalDays = 0;
                    
                    // 过滤掉不完整的打卡记录（只有签到或只有签退）
                    for (AttendanceRecord record : records) {
                        if (record.isCompleted() && "正常".equals(record.getAttendanceType())) {
                            normalDays++;
                        }
                    }
                    
                    // 计算出勤率
                    final int totalWorkingDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                    final float attendanceRate = totalWorkingDays > 0 ? (float) normalDays / totalWorkingDays * 100 : 0;
                    
                    // 在主线程更新UI
                    if (getActivity() != null) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                attendanceRateTextView.setText(String.format(Locale.getDefault(), "%.1f%%", attendanceRate));
                            }
                        });
                    }
                } catch (Exception e) {
                    Log.e("HomeFragment", "计算出勤率失败: " + e.getMessage(), e);
                    // 出错时显示默认值
                    if (getActivity() != null) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                attendanceRateTextView.setText("0.0%");
                            }
                        });
                    }
                }
            }
        }).start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 清理资源
        if (carouselHandler != null) {
            carouselHandler.removeCallbacksAndMessages(null);
            carouselHandler = null;
        }
        if (refreshHandler != null) {
            refreshHandler.removeCallbacksAndMessages(null);
            refreshHandler = null;
        }
    }
}